﻿CREATE FUNCTION [dbo].[RATExByPaymentFactor]( -- LAST
	@PF float,@PmtsPerYear tinyint,@Term smallint,@OpenDate smalldatetime,@FstDueDate smalldatetime,@DayCountConvention tinyint
)RETURNS float WITH SCHEMABINDING
BEGIN

IF ISNULL(@Term,0) = 0 RETURN 0

DECLARE @FNP int,@ODF float,@PMT numeric(18,2)
DECLARE @PFx float/*Payment Factor*/

SELECT @FNP=PeriodsToFstPmt,@ODF=OddDaysFactor FROM dbo.LoanBreakDown(@PmtsPerYear,@OpenDate,@FstDueDate,@DayCountConvention)

DECLARE @PR numeric(10,7) ,@PRx float/*Periodic Rate*/SELECT @PR = 0, @PRx = .1/@PmtsPerYear

WHILE @PR <> ROUND(@PRx,7) BEGIN
	SET @PR = @PRx
	SET @PFx = ((1.0-1.0/POWER((1.0+@PRx),@Term))/@PRx)*((POWER((1.0+@PRx),(1.0-@FNP)))/(1.0+(@PRx*@ODF)))
	SET @PRx = @PRx/@PF*@PFx
END

RETURN (ROUND(@PRx,7)*@PmtsPerYear)
END

